require 'RMagick'

class Image < ActiveRecord::Base
=begin
   file_column :filename,
    :root_path => "#{Rails.root}/public/images",
    :web_root => "images/",                     # 画像保存先ディレクトリ
    :magick => {
      :versions => {
        :thumb => { :crop => "1:1", :size => "50x50" }, # サムネイル画像の比率・サイズ指定
        :middle => "150x150>",                          # 中サイズ画像のサイズ指定
        :large => "480x480>"                            # 大サイズ画像のサイズ指定
      }
    }
=end
  def save_to_file(up_f)
    last_id = Image.last.id
    filename = "#{Rails.root}" + '/public/assets/images/image/' + last_id.to_s + '.jpg'
    File.open(filename, "wb") do |of|
      of.write(up_f.read)
      #ファイル保存
      img = ::Magick::Image::read(filename).first
      #bigsize
      bs_filename = "#{Rails.root}" + '/public/assets/images/image/big/' + last_id.to_s + '.jpg'
      if img.columns > img.rows
        dx, dy = 800, 520
      else
        dx, dy = 520, 800
      end
      img.resize(dx, dy).write(bs_filename)
      #middlesize
      ms_filename = "#{Rails.root}" + '/public/assets/images/image/middle/' + last_id.to_s + '.jpg'
      if img.columns > img.rows
        dx, dy = 600, 390
      else
        dx, dy = 390, 600
      end
      img.resize(dx, dy).write(ms_filename)
      #thumbnail
      thumb_filename = "#{Rails.root}" + '/public/assets/images/image/thumb/' + last_id.to_s + '.jpg'
      if img.columns > img.rows
        dx, dy = 200, 130
      else
        dx, dy = 130, 200
      end
      img.resize(dx, dy).write(thumb_filename)
    end
  end
end
